<template>
  <div class="domain-container">
    <edu-page-tabs :tab-list="tabs" />
    <el-form
      ref="domain-form"
      v-loading="loading"
      :model="formData"
      size="small"
      label-width="242px"
      label-position="right"
      label-suffix="："
      :rules="rules"
      class="domain-form"
    >
      <el-form-item label="当前生效域名">
        <el-link type="primary" :underline="false" target="_blank" :href="formData.effective_domain">{{ formData.effective_domain }}</el-link>
      </el-form-item>
      <el-form-item label="域名模式" prop="node">
        <el-radio-group v-model="formData.node" type="border" :disabled="confirmDisabled">
          <el-radio-button :label="1">二级域名</el-radio-button>
          <el-radio-button :label="2">自定义域名</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!-- 二级域名 start -->
      <el-form-item v-if="formData.node===1" label="域名设置" prop="sub_domain_prefix">
        <el-input v-model="formData.sub_domain_prefix" class="input-domain" :disabled="confirmDisabled" maxlength="30">
          <template slot="append">{{ formData.sub_domain_suffix }}</template>
        </el-input>
      </el-form-item>
      <!-- 二级域名 end -->
      <!-- 自定义域名 start -->
      <div v-else-if="formData.node === 2">
        <el-form-item label="CNAME值" prop="cname">
          <el-row type="flex">
            <div>{{ formData.cname || '-' }}</div>
            <el-button
              v-clipboard:copy="formData.cname"
              v-clipboard:success="copySuccess"
              type="primary"
              class="line-button"
              size="mini"
            >
              复制
            </el-button>
          </el-row>
          <div class="edu-tips">请在域名服务器网站上添加CNAME记录，指向该地址</div>
        </el-form-item>
        <el-form-item label="自定义域名" prop="domain">
          <el-row type="flex" align="middle">
            <el-input v-model="formData.domain" class="input-domain" :disabled="confirmDisabled"></el-input>
            <div class="check">
              <el-button
                type="primary"
                plain
                :disabled="formData.domain === ''"
                class="line-button"
                @click="checkDomain"
              >
                {{ domainChecked === 0 ? '检测' : '重新检测' }}
              </el-button>
              <span v-show="domainStatus === 0" class="error"><i class="el-icon-error"></i>未通过</span>
              <span v-show="domainStatus === 1" class="success"><i class="el-icon-success"></i>正常</span>
              <span v-show="domainStatus === 2" class="waiting"><i class="el-icon-loading"></i>检测中</span>
            </div>

          </el-row>
          <div class="edu-tips">1、域名不包含域名前缀（http://或https://）</div>
          <div class="edu-tips">2、填写域名后，请点击检测按钮，显示“正常”表示cname解析正确</div>
          <div class="edu-tips">2、域名设置成功后，请务必保留cname解析，否则将可能导致无法正常使用</div>
        </el-form-item>
        <el-form-item label="是否启用HTTPS">
          <el-switch
            v-model="formData.is_ssl"
            :active-value="1"
            :inactive-value="0"
            :disabled="confirmDisabled"
          ></el-switch>
        </el-form-item>
        <el-form-item v-if="formData.is_ssl === 1" label="SSL证书" prop="ssl">
          <div class="ssl-cert">
            <el-upload
              action=""
              :http-request="fileUpload"
              :limit="1"
              :before-upload="beforeUpload"
              :on-success="fileOnSuccessPem"
              :on-remove="handlerRemovePem"
              accept=".pem,.crt"
              :disabled="confirmDisabled"
              class="upload-btn"
            >
              <el-button type="primary">上传证书文件</el-button>
            </el-upload>
            <el-upload
              action=""
              :http-request="fileUpload"
              :limit="1"
              :before-upload="beforeUpload"
              :on-success="fileOnSuccessKey"
              :on-remove="handlerRemoveKey"
              accept=".key"
              :disabled="confirmDisabled"
              class="upload-btn"
            >
              <el-button type="primary">上传密钥文件</el-button>
              <div slot="tip" class="el-upload__tip">
                <div class="edu-tips">1、需要从购买证书的服务网站上下载Nginx证书后在这里上传</div>
                <div class="edu-tips">2、为保证后续网站能够正常使用，配置成功后，请确保证书的有效性</div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </div>
      <!-- 自定义域名  end -->
      <el-form-item>
        <el-row type="flex" class="confirm-box">
          <el-button
            :loading="confirmLoading"
            :disabled="disabledBtn"
            type="primary"
            size="small"
            @click="handlerConfirm"
          >
            提交审核
          </el-button>
        </el-row>
        <!-- 状态提醒 start-->
        <div>
          <el-alert
            v-if="formData.status === 2"
            title="审核中，暂不支持修改操作"
            type="warning"
            show-icon
            class="audit-message"
            :closable="false"
          >
          </el-alert>
          <el-alert
            v-else-if="formData.status === 0 && formData.audit_reason"
            :title="`申请已被驳回：【${formData.audit_reason}】，请调整后重新申请`"
            type="error"
            show-icon
            class="audit-message"
            :closable="false"
          >
          </el-alert>
        </div>
        <!-- 状态提醒 end-->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import EduPageTabs from '@public/template/tabs/page_tabs.vue'
import { mapGetters } from 'vuex'

export default {
  name: 'Domain',
  components: {
    EduPageTabs
  },
  inject: ['reload'],
  data() {
    return {
      loading: true,
      tabs: [
        {
          title: '域名配置',
          uri: '/site/website/domain',
          meta: {
            permission: 'site.website.domain'
          }
        }
      ],
      rules: {
        node: [
          { required: true, message: '请选择域名模式', trigger: ['blur', 'change'] }
        ],
        sub_domain_prefix: [
          { required: true, message: '请填写二级域名', trigger: ['blur', 'change'] },
          {
            validator: (rule, value, callback) => {
              const reg = /^[\w\-]+$/;
              if (!reg.test(value)) {
                return callback(new Error('域名只能由数字字母、中横线组成'));
              }
              callback();
            },
            trigger: ['blur', 'change']
          }
        ],
        domain: [
          { required: true, message: '请填写域名', trigger: ['blur', 'change'] },
          {
            pattern: /^[\w\.\u4e00-\u9fa5]+\.[a-z]+$/,
            message: '请输入正确的域名',
            trigger: ['blur', 'change']
          }
        ],
        ssl: [
          {
            validator: (rule, value, callback) => {
              if (this.formData.is_ssl === 1 && !this.formData.ssl_pem) {
                return callback(new Error('请上传证书文件'))
              } else if (this.formData.is_ssl === 1 && !this.formData.ssl_key) {
                return callback(new Error('请上传密钥文件'))
              }
              callback()
            },
            trigger: ['blur', 'change']
          }
        ]
      },
      formData: {
        domain: '',
        is_ssl: 0,
        ssl_pem: 0,
        ssl_key: 0,
        node: 1,
        sub_domain: '',
        sub_domain_prefix: ''
      },
      domainChecked: 0,
      domainStatus: 3,
      confirmLoading: false,
      confirmDisabled: false
    }
  },
  computed: {
    ...mapGetters('login', ['mhmId']),
    disabledBtn() {
      if (this.formData.node === 1) {
        return this.confirmDisabled || this.formData.sub_domain_prefix === ''
      } else {
        return this.confirmDisabled || this.domainStatus !== 1
      }
    }
  },
  mounted() {
    if (this.mhmId === 1) {
      this.$router.push('/');
      return
    }
    this.$store.dispatch('setLoading', 0);
  },
  created() {
    this.getDomainInfo()
  },
  methods: {
    copySuccess() {
      this.$message.success('复制成功')
    },
    /** 自定义文件上传方法,采用分片上传 */
    fileUpload: function (params) {
      // 指定为临时文件
      params.is_temp = true
      // 分片上传 每2M为一片
      this.$upload.submit(params, true, 2);
    },
    beforeUpload(file) {
      // 检测大小
      const isLt1M = file.size / 1024 / 1024 <= 1;
      if (!isLt1M) {
        this.$message.error('最大只能上传1M的文件');
        return false;
      }

      return true;
    },
    fileOnSuccessPem(response, file) {
      this.formData.ssl_pem = file.id || response.data.id
    },
    handlerRemovePem() {
      this.formData.ssl_pem = 0
    },
    fileOnSuccessKey(response, file) {
      this.formData.ssl_key = file.id || response.data.id
    },
    handlerRemoveKey() {
      this.formData.ssl_key = 0
    },
    // 获取域名信息
    getDomainInfo() {
      this.$http.get(
          '/school/admin/domain/info',
          {},
          ({ data }) => {
            this.formData = { ...this.formData, ...data }
            this.domainStatus = data.cname_status
            if (data.status === 2) {
              this.confirmDisabled = true
            }
            this.loading = false
          },
          ({ msg }) => {
            this.$message.error(msg)
            this.loading = false
          },
          false
      )
    },
    // 检测域名
    checkDomain() {
      this.domainChecked = 1
      this.domainStatus = 2;
      this.$http.post(
          '/school/admin/domain/check',
          {
            domain: this.formData.domain
          },
          ({ data }) => {
            const {
              status
            } = data
            this.domainStatus = status
          },
          ({ msg }) => {
            this.$message.error(msg)
          },
          false
      )
    },
    // 提交审核
    handlerConfirm() {
      this.$refs['domain-form'].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          this.confirmDisabled = true
          this.$http.post(
              '/school/admin/domain/create',
              this.formData,
              ({ msg }) => {
                this.$message.success(msg)
                this.reload()
              },
              ({ msg }) => {
                this.$message.error(msg)
                this.confirmLoading = false
                this.confirmDisabled = false
              },
              false
          )
        }
      })
    }
  }
}

</script>

<style scoped lang="scss">
.domain-container {
  .line-button {
    margin-left: 6px;
  }

  .input-domain {
    width: 442px;
  }

  .check {
    span {
      margin-left: 4px;

      &.success {
        color: #67C23A;
      }

      &.error {
        color: #F54030;
      }

      &.waiting {
        color: #909399;
      }
    }
  }

  .audit-message {
    margin-top: 10px;
    width: max-content;
  }

  .confirm-box {
    margin-top: 40px;
  }

  .ssl-cert {
    width: 442px;
    .upload-btn{
      margin-top: 10px;
      &:first-child{
        margin-top: 0;
      }
    }
  }
}
</style>
